package com.yzd.netmonitor.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;

/**
 * 系统 IO 操作辅助类.
 * @author YRJ
 *
 */
public final class IOHelper {

	/**
	 * 关闭输出流.
	 * @param output
	 */
	public static void closeOutput(final OutputStream output) {
		if (output != null) {
			try {
				output.flush();
				output.close();
			} catch (final IOException ignore) {
			}
		}
	}

	/**
	 * 关闭输入流.
	 * @param input
	 */
	public static void closeInput(final InputStream input) {
		if (input != null) {
			try {
				input.close();
			} catch (final IOException ignore) {
			}
		}
	}

	/**
	 * 关闭读取流.
	 * @param reader
	 */
	public static void closeReader(final Reader reader) {
		if (reader != null) {
			try {
				reader.close();
			} catch (final IOException ignore) {
			}
		}
	}

	/**
	 * 拷贝流. 从输入流 input 写入到输出流 output.
	 * @param input
	 * @param output
	 */
	public static void copyStream(final InputStream input, final OutputStream output) {
		final byte[] buf = new byte[1024];
		int len;

		try {
			while ((len = input.read(buf)) != -1) {
				output.write(buf, 0, len);
			}
		} catch (final IOException e) {
			e.printStackTrace();
		}
	}

	public static final byte[] inputStreamToByte(InputStream inStream) throws IOException {
		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
		byte[] buff = new byte[100];
		int rc = 0;
		while ((rc = inStream.read(buff, 0, 100)) > 0) {
			swapStream.write(buff, 0, rc);
		}
		byte[] in2b = swapStream.toByteArray();
		return in2b;
	}

	public static void inputStreamToFile(InputStream ins, File file) {
		OutputStream os = null;
		try {
			os = new FileOutputStream(file);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		try {
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			os.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			ins.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private IOHelper() {
		throw new AssertionError("Uninstantiable class.");
	}
}